package gate

import (
	"server/share"
	"strconv"
	"strings"
	"time"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/cosgo/session"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/cosnet"
	"github.com/hwcer/logger"
	"github.com/hwcer/yyds/gateway"
	"github.com/hwcer/yyds/options"
)

var (
	_ = share.Loading
)
var m = &Module{}

func init() {
	m.Module = *gateway.New()
	cosnet.On(cosnet.EventTypeError, m.Error)
	gateway.Options.Router = m.route
	gateway.Options.C2SOAuth = "/:sid/login"
	gateway.Options.G2SOAuth = "game/oauth"
	session.Options.Name = "_bong_id"
	gateway.ElapsedMillisecond = 500 * time.Millisecond
}

func New() *Module {
	return m
}

type Module struct {
	gateway.Module
}

func (this *Module) Init() error {
	if err := this.Module.Init(); err != nil {
		return err
	}
	return nil
}

func (this *Module) Error(sock *cosnet.Socket, v any) {
	logger.Debug("Error:%v", v)
	if sock == nil {
		return
	}
	err := values.Error(v)
	sock.Send(0, "Error", err)
}

func (this *Module) route(path string, req values.Metadata) (servicePath, serviceMethod string, err error) {
	path = strings.TrimPrefix(path, "/")
	i := strings.Index(path, "/")
	if i < 0 {
		err = values.Errorf(404, "page not found")
		return
	}
	//判断
	s := strings.ToLower(path[0:i])
	if sid := isServerID(s); sid > 0 {
		req.Set(options.SelectorServerId, sid)
		servicePath = options.ServiceTypeGame
	} else {
		servicePath = s
	}
	serviceMethod = registry.Formatter(path[i:])
	serviceMethod = strings.TrimSuffix(serviceMethod, "/")
	return
}

func isServerID(s string) int32 {
	if !strings.HasPrefix(s, "s") {
		return 0
	}
	s = strings.TrimPrefix(s, "s")
	v, _ := strconv.ParseInt(s, 10, 64)
	return int32(v)
}
